/*
 * 24cxx.c
 *
 *  Created on: Sep 30, 2022
 *      Author: 31866
 */
#include "24cxx.h"

/*向EEPROM读取一个字节*，返回值为一个字节。ReadAddr是读取的寄存器地址*/
uint8_t HAL_AT24CXX_ReadOneByte(uint16_t ReadAddr)
{
	uint8_t rxdata=0;  //用于存放数据并返回
	if(EE_TYPE<AT24C16)
	{
		HAL_I2C_Mem_Read(&hi2c1,AT24C_DEV_READADDR,ReadAddr,1,&rxdata,1,0XFFFF);
	}
	else
	{
		HAL_I2C_Mem_Read(&hi2c1,AT24C_DEV_READADDR,ReadAddr,2,&rxdata,1,0XFFFF);
	}
	HAL_Delay(10);
	return rxdata;
}

uint8_t HAL_AT24CXX_WriteOneByte(uint16_t WriteAddr,uint8_t WriteData)
{
	uint8_t res=1;
	if(EE_TYPE<AT24C16)
	{
		if(HAL_I2C_Mem_Write(&hi2c1,AT24C_DEV_WRITEADDR,WriteAddr,1,&WriteData,1,0XFFFF)==HAL_OK)
			res=0;   //等于0则说明写入成功
	}
	else
	{
		if(HAL_I2C_Mem_Write(&hi2c1,AT24C_DEV_WRITEADDR,WriteAddr,2,&WriteData,1,0XFFFF)==HAL_OK)
			res=0;
	}
	HAL_Delay(10);
	return res;
}

/*向EEPROM写入指定长度的字节，循环利用WriteOneByte函数写入。pData是一个数组*/
void HAL_AT24CXX_WriteLenByte(uint16_t WriteAddr,uint8_t *pData,uint8_t dataLen)
{
	while(dataLen--)
	{
		HAL_AT24CXX_WriteOneByte(WriteAddr,*pData);
		WriteAddr++;
		pData++;   //指向下一个索引的数
	}
}

/*向EEFPROM读取指定字节的数据*/
void HAL_AT24CXX_ReadLenByte(uint16_t ReadAddr,uint8_t *pData,uint8_t dataLen)
{
	while(dataLen--)
	{
		*pData++=HAL_AT24CXX_ReadOneByte(ReadAddr++);
	}
}

/**/
bool HAL_AT24CXX_Check(void)
{
	uint8_t temp;
	temp=HAL_AT24CXX_ReadOneByte(EE_TYPE);
	printf("temp:%d\n",temp);
	if(temp==0xAB)
		return true;
	else
	{
		HAL_AT24CXX_WriteOneByte(EE_TYPE,0XAB);
		temp=HAL_AT24CXX_ReadOneByte(EE_TYPE);
		if(temp==0XAB)
			return true;
	}
	return false;
}

